<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>🎉 抽奖小助手</title>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
      body {
        font-family: "Microsoft YaHei", sans-serif;
        margin: 0;
        background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
        overflow-x: hidden;
      }
      h1 {
        text-align: center;
        padding: 20px;
        color: #d81b60;
        text-shadow: 2px 2px 6px rgba(0, 0, 0, 0.2);
      }
      .container {
        display: flex;
        flex-wrap: wrap;
        padding: 15px;
        gap: 15px;
        justify-content: center;
      }
      .panel {
        flex: 1 1 300px;
        background: #fff;
        border-radius: 16px;
        padding: 20px;
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        min-height: 200px;
      }
      textarea,
      input[type="file"] {
        width: 100%;
        margin: 5px 0;
      }
      button {
        padding: 12px 20px;
        margin: 6px 4px;
        border: none;
        border-radius: 50px;
        font-size: 16px;
        cursor: pointer;
        transition: all 0.2s;
      }
      button:hover {
        transform: scale(1.05);
      }
      .start {
        background: #e91e63;
        color: #fff;
        font-size: 20px;
      }
      .stop {
        background: #4caf50;
        color: #fff;
        font-size: 20px;
      }
      .result {
        font-size: 48px;
        text-align: center;
        margin-top: 20px;
        color: #ff5722;
        font-weight: bold;
        text-shadow: 0 0 12px #fff, 0 0 20px gold;
      }
      .history {
        max-height: 200px;
        overflow-y: auto;
        font-size: 15px;
      }
      .winner {
        background: #fce4ec;
        border-radius: 8px;
        padding: 6px;
        margin: 4px 0;
      }
      .ranking {
        font-size: 15px;
        margin-top: 10px;
      }
      .bullet {
        position: fixed;
        white-space: nowrap;
        font-size: 22px;
        font-weight: bold;
        animation: move 8s linear;
      }
      @keyframes move {
        from {
          left: 100%;
        }
        to {
          left: -300px;
        }
      }
    </style>
  </head>
  <body>
    <h1>🎉 抽奖小助手</h1>

    <div class="container">
      <!-- 左侧：名单导入 -->
      <div class="panel">
        <h3>📋 导入名单</h3>
        <textarea id="nameList" placeholder="每行输入一个名字"></textarea>
        <input
          type="file"
          id="excelFile"
          accept=".xlsx"
          onchange="importExcel(event)"
        />
        <button onclick="importNames()">导入文本名单</button>
        <ul id="studentList"></ul>
      </div>

      <!-- 中间：抽奖区 -->
      <div class="panel" style="text-align: center">
        <h3>🎁 抽奖设置</h3>
        <label
          >抽取人数:
          <input type="number" id="numWinners" value="1" min="1" /></label
        ><br /><br />
        <label><input type="checkbox" id="allowRepeat" /> 允许重复中奖</label
        ><br /><br />
        <label
          >奖品名称:
          <input
            type="text"
            id="prizeName"
            placeholder="如：糖果 / 小贴纸" /></label
        ><br /><br />
        <button class="start" onclick="startLottery()">开始抽奖</button>
        <button class="stop" onclick="stopLottery()">停止抽奖</button>
        <div class="result" id="result">等待抽奖...</div>
      </div>

      <!-- 右侧：结果区 -->
      <div class="panel">
        <h3>🏆 历史中奖</h3>
        <div id="history" class="history"></div>
        <h3>📊 排行榜</h3>
        <div id="ranking" class="ranking"></div>
      </div>
    </div>

    <audio
      id="tickSound"
      src="https://actions.google.com/sounds/v1/alarms/beep_short.ogg"
    ></audio>
    <audio
      id="winSound"
      src="https://actions.google.com/sounds/v1/cartoon/clang_and_wobble.ogg"
    ></audio>

    <script>
      let students = [];
      let winnersHistory = [];
      let ranking = {};
      let rollingInterval = null;

      // 导入 Excel 文件
      function importExcel(e) {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = function (evt) {
          const data = new Uint8Array(evt.target.result);
          const workbook = XLSX.read(data, { type: "array" });
          const sheet = workbook.Sheets[workbook.SheetNames[0]];
          const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 });
          students = rows.flat().filter((n) => n);
          renderStudentList();
          alert("Excel 导入成功！共 " + students.length + " 个名字");
        };
        reader.readAsArrayBuffer(file);
      }

      // 导入文本框名单
      function importNames() {
        const text = document.getElementById("nameList").value.trim();
        students = text
          .split("\n")
          .map((n) => n.trim())
          .filter((n) => n);
        renderStudentList();
        alert("导入成功！共 " + students.length + " 个名字");
      }

      // 渲染名单
      function renderStudentList() {
        const ul = document.getElementById("studentList");
        ul.innerHTML = "";
        students.forEach((name) => {
          const li = document.createElement("li");
          li.textContent = name;
          ul.appendChild(li);
        });
      }

      function startLottery() {
        if (students.length === 0) {
          alert("请先导入名单！");
          return;
        }
        const resultBox = document.getElementById("result");
        const tick = document.getElementById("tickSound");
        rollingInterval = setInterval(() => {
          const rand = students[Math.floor(Math.random() * students.length)];
          resultBox.textContent = rand;
          tick.play();
        }, 80);
      }

      function stopLottery() {
        if (!rollingInterval) return;
        clearInterval(rollingInterval);
        rollingInterval = null;

        const num = parseInt(document.getElementById("numWinners").value) || 1;
        const allowRepeat = document.getElementById("allowRepeat").checked;
        const prize = document.getElementById("prizeName").value || "奖品";

        let pool = [...students];
        let selected = [];
        for (let i = 0; i < num; i++) {
          if (pool.length === 0) break;
          const randIndex = Math.floor(Math.random() * pool.length);
          selected.push(pool[randIndex]);
          if (!allowRepeat) pool.splice(randIndex, 1);
        }

        const resultText =
          "🎉 " + selected.join(", ") + " 获得【" + prize + "】";
        document.getElementById("result").textContent = resultText;

        winnersHistory.push(resultText);
        updateHistory();
        updateRanking(selected);

        document.getElementById("winSound").play();
        launchBullets(selected, prize);
      }

      function updateHistory() {
        const box = document.getElementById("history");
        box.innerHTML = "";
        winnersHistory
          .slice(-10)
          .reverse()
          .forEach((item) => {
            const div = document.createElement("div");
            div.className = "winner";
            div.textContent = item;
            box.appendChild(div);
          });
      }

      function updateRanking(selected) {
        selected.forEach((name) => {
          ranking[name] = (ranking[name] || 0) + 1;
        });
        const box = document.getElementById("ranking");
        box.innerHTML = "";
        Object.entries(ranking)
          .sort((a, b) => b[1] - a[1])
          .forEach(([name, count]) => {
            const div = document.createElement("div");
            div.textContent = `${name}: ${count} 次`;
            box.appendChild(div);
          });
      }

      function launchBullets(names, prize) {
        names.forEach((name) => {
          for (let i = 0; i < 5; i++) {
            const span = document.createElement("span");
            span.className = "bullet";
            span.textContent = `🎉 恭喜 ${name} 获得【${prize}】`;
            span.style.top = Math.random() * 80 + "%";
            span.style.color = ["#e91e63", "#4caf50", "#ff9800", "#2196f3"][
              Math.floor(Math.random() * 4)
            ];
            document.body.appendChild(span);
            setTimeout(() => span.remove(), 8000);
          }
        });
      }
    </script>
  </body>
</html>